<?php

namespace App\Http\Controllers\Api;

use App\Models\Log;
use App\Models\Photo;
use App\Models\Plan;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class HomeController extends Controller
{
    /**
     * 后台首页统计数据
     * @return mixed
     */
    public function index()
    {
        if ($this->user()->isAdmin()) {
            $query = Log::query();
        } else {
            $query = $this->user()->logs();
        }
        $logs = $query
            ->with('user:id,name')
            ->orderBy('id', 'desc')
            ->limit(5)
            ->get(); //最近登录日志

        $login = $this->user()->logs()->orderBy('id', 'desc')->first(); //最近登录时间
        $login->date = $login->created_at->diffForHumans();

        // 统计数据
        $statistics = [
            'plan_count' => Plan::count(),
            'user_count' => User::count(),
            'photo_count' => Photo::count(),
            'retouch_count' => Photo::where('retouch', 1)->count()
        ];

        // 拍摄分布
        $status = Plan::select(DB::raw('count(*) as value, status as name'))
            ->groupBy('status')
            ->get()
            ->toArray();

        $data = [];
        foreach (Plan::$statusMap as $key => $val) {
            $data[] = [
                'name' => $key,
                'value' => 0
            ];
        }
        foreach ($data as $key => $val) {
            foreach ($status as $v) {
                if ($v['name'] === $val['name']) {
                    $data[$key] = array_merge($val, $v);
                }
            }
        }
        foreach ($data as &$val) {
            $val['name'] = Plan::$statusMap[$val['name']];
        }

        return $this->success(compact('logs', 'login', 'statistics', 'data'));
    }
}
